const express = require('express')
const router = express.Router()
const { sqlHandler } = require("../db")
// let data = {
//     data: [{user: '1111111',name: 'cxl',id:1,price: 1000,type: 'eat',data: '2021-01-01'},{name: 'cxl',id:1,price: 1000,type: 'eat',data: '2021-01-01'},{name: 'cxl',id:1,price: 1000,type: 'eat',data: '2021-01-01'}],
//     status: {
//         code: 200,
//         msg: "ok"
//     }
// }

router.get('/list', async (req, res) => {
    if (req?.query?.userid) {
        console.log("userid", req.query);
        let sql = `select * from billList where userid=${req.query.userid}`
        let result = await sqlHandler(sql)
        res.send(result)
        return
    }
    res.send()
})

router.post("/new", async (req, res) => {
    const { name, userid, date, spend, type, price } = req.body
    console.log("xxxxxxxxx", name, userid, date, spend, type, price);
    let sql = `insert into billList (name,userid,date,spend,type,price) values ('${name}',${userid},${date},${spend},'${type}',${price})`
    let result
    try {
        result = await sqlHandler(sql)
    } catch (error) {
        result = JSON.stringify(error)
    }
    console.log("插入结果", result);
    res.send(result)
})

router.post('/register', async (req, res) => {
    console.log("register", req.body);
    let sql = `insert into user (displayname,username,password,email,phone) values ('${req.body.displayname}','${req.body.username}','${req.body.password}','${req.body.email}','${req.body.phone}')`
    let result = await sqlHandler(sql)
    if (result) {
        sql = `select * from user where username = '${req.body.username}' and password = '${req.body.password}'`
        result = await sqlHandler(sql)
    }
    res.send(result)
})
router.post('/login', async (req, res) => {
    console.log("login", req.body);
    let sql = `select * from user where username = '${req.body.username}' and password = '${req.body.password}'`
    const result = await sqlHandler(sql)
    if (result) {
        res.send(result[0])
    } else {
        res.send('')
    }
})
module.exports = router